package org.szgb.console.sys.dict.web;

import cn.hutool.http.HttpStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.szgb.console.sys.dict.entity.SysDict;
import org.szgb.console.sys.dict.entity.SysDictChildren;
import org.szgb.console.sys.dict.service.SysDictChildrenService;
import org.szgb.console.sys.dict.service.SysDictService;
import org.szgb.console.sys.user.entity.SysUser;
import org.szgb.console.utils.PageView;
import org.szgb.console.utils.TokenUtil;
import org.szgb.core.utils.AjaxJson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/sys/dict")
@Tag(name = "字典管理", description = "字典管理模块")
public class SysDictController {
    private final SysDictService sysDictService;
    private final SysDictChildrenService sysDictChildrenService;

    @Autowired
    public SysDictController(SysDictService sysDictService, SysDictChildrenService sysDictChildrenService) {
        this.sysDictService = sysDictService;
        this.sysDictChildrenService = sysDictChildrenService;
    }


    @Operation(summary = "获取字典信息", description = "根据查询参数获取字典信息，支持分页查询。使用id获取更详细的信息。")
    @PostMapping("/get")
    public AjaxJson get(@RequestBody(required = false) SysDict.SysDictFindDto sysDictFindDto, HttpServletRequest request, HttpServletResponse response) {
        if (sysDictFindDto == null) {
            sysDictFindDto = new SysDict.SysDictFindDto();
        }
        // 创建一个PageView对象，用于分页显示
        PageView<SysDict.SysDictView> pageView = new PageView<>();
        SysDict sysDict = sysDictFindDto.toSysDict();
        // 如果实体对象的ID不为空，则直接调用get方法获取单个实体对象
        if (sysDict != null && sysDict.getId() != null && !sysDict.getId().isEmpty()) {
            SysDict line = sysDictService.get(sysDict.getId());
            // 如果实体对象为空，则返回错误响应
            if (line == null) {
                return AjaxJson.error("数据不存在", HttpStatus.HTTP_NOT_FOUND, request, response);
            }
            // 返回成功的响应，并将实体对象放入响应中
            return AjaxJson.success(request, response).put("sysDict", line.toSysDictView());
        } else {
            // 设置Page对象的列表属性，包含根据实体对象查询到的数据
            pageView.setList(SysDict.SysDictView.getViewListFromList(sysDictService.findList(sysDict)));
            // 设置Page对象的总记录数属性，用于分页显示
            pageView.setCount(sysDictService.getCount(sysDict));
            // 创建一个成功的AjaxJson对象，并放入Page对象，以便于前端展示
            return AjaxJson.success(request, response).put("page", pageView);
        }
    }

    @PostMapping("/getTree")
    @Operation(summary = "获取字典树", description = "获取字典树信息(开销大少使用)")
    public AjaxJson getTree(HttpServletRequest request, HttpServletResponse response) {
        List<SysDict> sysDictList = sysDictService.findList(null);
        List<SysDictChildren> sysDictChildrenList = sysDictChildrenService.findList(null);
        Map<String, List<SysDictChildren.SysDictChildrenTreeView>> sysDictChildrenListMap = new HashMap<>();
        for (SysDictChildren sysDictChildren : sysDictChildrenList) {
            if (sysDictChildrenListMap.containsKey(sysDictChildren.getDict().getId())) {
                sysDictChildrenListMap.get(sysDictChildren.getDict().getId()).add(sysDictChildren.toSysDictChildrenTreeView());
            } else {
                List<SysDictChildren.SysDictChildrenTreeView> list = new java.util.ArrayList<>();
                list.add(sysDictChildren.toSysDictChildrenTreeView());
                sysDictChildrenListMap.put(sysDictChildren.getDict().getId(), list);
            }
        }
        List<SysDict.SysDictTreeView> dictTree = new ArrayList<>();
        sysDictList.forEach(sysDict -> dictTree.add(new SysDict.SysDictTreeView(sysDict, sysDictChildrenListMap.get(sysDict.getId()))));
        return AjaxJson.success(request, response).put("dictTree", dictTree);
    }

    @PostMapping("/save")
    @Operation(summary = "保存字典", description = "新增或更改字典信息。")
    public AjaxJson save(@RequestBody SysDict.SysDictSaveDto sysDictSaveDto, HttpServletRequest request, HttpServletResponse response) {
        if (sysDictSaveDto == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        SysDict sysDict = sysDictSaveDto.toSysDict();
        // 设置实体对象的更新者为当前用户
        sysDict.setUpdatedBy(new SysUser(TokenUtil.getUid(request)));
        // 调用服务层的save方法，尝试保存或更新实体对象，返回保存结果的Map
        sysDictService.save(sysDict);
        // 根据保存结果返回相应的AjaxJson对象
        return AjaxJson.success("保存成功", request, response).put("sysDict", sysDict.toSysDictView());
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除字典", description = "根据ID删除字典信息。", parameters = {@Parameter(name = "ids", description = "字典ID列表，多个ID用英文逗号分隔。")})
    public AjaxJson delete(@RequestParam String ids, HttpServletRequest request, HttpServletResponse response) {
        // 检查ID参数是否为空，为空则返回错误响应
        if (ids == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        // 调用服务层方法，执行删除操作
        sysDictService.delete(ids);
        // 返回成功响应
        return AjaxJson.success(request, response);
    }
}
